<template>
  <div class="search-page">
    <div class="search-box">
      <SearchWrap @search="handleSearch" />
      <!--      <div class="add-require" @click="showPopup">添加筛选</div>-->
    </div>
    <div class="pickwk" v-if="pickFlag">
      <van-field
        v-model="wkValue"
        is-link
        readonly
        label="微课类别:"
        placeholder="请选择类别"
        @click="showPicker1 = true"
      />

      <van-popup v-model:show="showPicker1" round position="bottom">
        <van-picker
          v-model="selectedValues1"
          :columns="wkList"
          @cancel="showPicker1 = false"
          @confirm="onConfirm1"
        />
      </van-popup>
    </div>
    <!-- 虚拟列表 -->
    <div class="list-box">
      <div class="isSearchLoading" v-show="isSearchLoading">正在搜索中...</div>
      <List v-show="!isSearchLoading" :finished="finished" @reFresh="handleRefresh" @loadData="getDataList">
        <ListItem v-for="item of dataList" :key="item" :item="item" @jump="handleVideoJump(item)"></ListItem>
      </List>
    </div>
    <!-- 底部弹出 -->
    <van-popup v-model:show="showBottom" round position="bottom" :style="{ height: '60%' }">
      <div class="popup-wrap">
        <div class="title">添加筛选</div>
        <TagsWrap title="视频标签" type="spdb_spgl_spbq" :dataList="videoTag"></TagsWrap>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { getHomeVideoList } from '@/api/parentClassroom.js';
import { getVideoHistoryList, getVideoLikeCollect, getVideoLikeList } from '@/api/videoPlay.js';
import TagsWrap from './components/TagsWrap/index.vue';
import { onMounted, toRefs, ref, reactive } from 'vue';
import { searchMenu } from '@/utils/enum.js';
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
import { usePageTitle, useDictSelect } from '@/store/base.js';



//  枚举 记录当前所有的选择
const pageMenu = {
  history: {
    text: '历史记录',
    func: getVideoHistoryList
  },
  search: '搜索页',
  introduce: {
    text: '视频推荐',
    func: getHomeVideoList
  },
  jzwk: {
    text: '家长微课',
    tag: '013',
    func: getHomeVideoList
  },
  hstj: {
    text: '好书推荐',
    tag: '007',
    func: getHomeVideoList
  },
  jjzx: '家教资讯',
  yexd: {
    text: '育儿心得',
    tag: '006',
    func: getHomeVideoList
  },
  collect: {
    text: '我的收藏',
    func: getVideoLikeCollect
  },
  dzlist: {
    text: '点赞列表',
    func: getVideoLikeList
  }
}

const parentId = JSON.parse(localStorage.getItem('parentId'));

const page = ref({
  currentPage: 1,
  pageSize: 20,
  title: '',
  parentId: parentId,
  sort: "desc",
  sidx: "publishTime"
});
const route = useRoute();
const router = useRouter();
const { pageTitle, setPageTitle } = usePageTitle();
const curStatus = ref(route.query.status || '');



const wkList = [
  { text: '泰州家长微课', value: '013' },
  { text: '泰州名师微课', value: '014' },
  { text: '江苏家长微课', value: '015' },
  { text: '江苏"三道"课程', value: '016' },
  { text: '其他家教课程', value: '017' }
]



const selectedValues1 = ref(['']);
const pickFlag = ref(false)
const showPicker1 = ref(false);
let wkValue = ref('');
if(curStatus.value=='jzwk'){
  wkValue = ref('泰州家长微课');
  pickFlag.value = true;
}else{
  pickFlag.value = false;
}
const wkId = ref('')
const onConfirm1 = ({ selectedOptions }) => {
  showPicker1.value = false;
  wkValue.value = selectedOptions[0]?.text;
  wkId.value = selectedOptions[0]?.value;
  page.value.videoLabel = JSON.stringify([wkId.value]);
  getwkList()
};

//  初始化数据
function initData() {
  const { text, tag } = pageMenu[curStatus.value];
  //  设置标题
  setPageTitle(text);

  if (tag) page.value.videoLabel = JSON.stringify([tag]);
}

const dataList = ref([]);
const finished = ref(false);

//  获取 videoTag 数据
const videoTag = ref([]);
const { dictSelectArray, setDictSelect } = useDictSelect();
const getTagList = () => {
  setDictSelect('spdb_spgl_spbq').then(res => {
  });
}

//  请求数据
async function getDataList() {
  if (finished.value) return;
  const status = route.query.status
  let method = pageMenu[curStatus.value].func;

  return await getMethods(method, status);
}

//选择微课类型请求数据
async function getwkList() {
  const pagewk = ref({
    currentPage: 1,
    pageSize: 500,
    title: '',
    parentId: parentId,
    sort: "desc",
    sidx: "publishTime",
    videoLabel: JSON.stringify([wkId.value])
  });
  isSearchLoading.value = true;
  dataList.value = []
  const { code, data } = await getHomeVideoList(pagewk.value);
  if (code == 200) {
    isSearchLoading.value = false;
    const { currentPage, pageSize, total } = data.pagination;
    // 判断是否到底
    if (currentPage * pageSize >= total) {
      finished.value = true;
    }
    //  格式化数据
    dataList.value = dataList.value.concat(setDataList(data.list))
  }
}

//  下拉刷新
const handleRefresh = () => {
  page.value.currentPage = 1;
  finished.value = false;
  dataList.value = []
  debounce(getDataList, 800)();
}

//  请求数据
async function getMethods(method, status) {
  if (!method) return [];
  if (finished.value) return;
  //  是否展示加载效果，主要针对首次
  if (page.value.currentPage === 1) {
    isSearchLoading.value = true;
  }
  const { code, data } = await method(page.value);
  isSearchLoading.value = false;


  if (code == 200) {
    const { currentPage, pageSize, total } = data.pagination;
    //  判断是否是第一页，是的话就清空，避免重复请求
    if (currentPage === 1) {
      dataList.value = [];
    }

    // 判断是否到底
    if (currentPage * pageSize >= total) {
      finished.value = true;
    }

    //  格式化数据
    let _d = [];
    if (status === 'history') {
      _d = setHistoryDataList(data.list);
    } else if (status === 'collect') {
      _d = setCollectDataList(data.list);
    } else {
      _d = setDataList(data.list);
    }

    dataList.value = dataList.value.concat(_d);

    page.value.currentPage++;
  }
}

//  监听路由参数变更 清空之前的数据
onBeforeRouteLeave((to, from) => {
  dataList.value = [];
  finished.value = false;
})

// 切换路由参数，实现播放
const handleVideoJump = (data) => {
  //  获取 videoId 跳转到详情页
  const { videoId = '' } = data;
  router.push({ path: `/VideoPlay/${videoId}` });
}

//  处理搜索数据格式
function setDataList(data) {
  const _data = [...data].map(item => {
    //  处理图片
    try {
      item.videoPic = JSON.parse(item.videoPic);
      item.image = item.videoPic[0] ? (process.env.VITE_API_API_IMAGE_URL + item.videoPic[0].url) : '';
    } catch (ev) {
      item.image = '';
    }
    return item;
  });

  return _data;
}

//  处理收藏数据
function setCollectDataList(data) {
  const _data = [...data].map(item => {
    const _d = item.spgl_video
    if (_d) {
      item.title = _d.title;
      item.publishTime = _d.publishTime;
      item.publisher = _d.publisher;
      item.playCount = _d.playCount;
      item.videoId = _d.videoId;

      try {
        const videoPic = JSON.parse(_d.videoPic);
        item.image = videoPic[0].url ? process.env.VITE_API_API_IMAGE_URL + videoPic[0].url : '';
      } catch (ev) {
        item.image = '';
      }
    }

    return item;
  })
  return _data;
}

//  处理 history 列表参数
function setHistoryDataList(data) {
  const _data = [...data].map(item => {
    if (item.spgl_video) {
      item.title = item.spgl_video.title;
      item.playCount = item.spgl_video.playCount;
      item.publisher = item.spgl_video.publisher
    } else {
      item.title = '';
      item.playCount = '';
    }

    if (item.spdb_parent) {
      // item.publisher = item.spdb_parent.realName;
    }

    item.publishTime = item.playTime;

    try {
      const videoPic = JSON.parse(item.spgl_video.videoPic);
      item.image = videoPic[0].url ? process.env.VITE_API_API_IMAGE_URL + videoPic[0].url : '';
    } catch (ev) {
      item.image = '';
    }

    return item;
  })
  return _data;
}

onMounted(() => {
  initData();
  // resolvePageTitle();
  getDataList();
  //  获取 视频标签
  getTagList();
})

// 搜索
function handleSearch(val) {
  page.value.title = val;
  page.value.currentPage = 1;
  finished.value = false;
  isSearchLoading.value = true;
  debounce(getDataList, 800)();
}

//  防抖
function debounce(func, delay) {
  let timeout
  return function () {
    const _this = this
    const args = [...arguments]
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      func.apply(_this, args)
    }, delay)
  }
}

//  控制加载显示
const isSearchLoading = ref(false);

//  控制弹窗显示
const showBottom = ref(false);
const showPopup = () => {
  showBottom.value = true;
};
</script>

<style lang="scss" scoped>
.isSearchLoading {
  height: 10rem;
  text-align: center;
  line-height: 10rem;
  font-size: 1.4rem;
}

.list-box {
  flex: 1;
  box-sizing: border-box;
}

.search-page {
  padding: 0 1.4rem;
  box-sizing: border-box;

  .search-box {
    width: 100%;
    display: flex;
    align-items: end;
    padding: 1rem 0;
    box-sizing: border-box;

    .add-require {
      width: 8rem;
      text-align: right;
      font-size: 1.4rem;
      color: rgb(22, 155, 213);
    }
  }
}

.popup-wrap {
  .title {
    height: 5rem;
    line-height: 5rem;
    text-align: center;
    font-size: 1.6rem;
    border-bottom: .1rem solid #ccc;
  }
}
::v-deep .van-field{
  width: 14rem;
  padding: 0 0.5rem 0 0;
  margin-bottom: 1rem;
  border-radius: 1.2rem;
}
::v-deep .van-field__label{
  // width: 0;
  display: none;
}
::v-deep .van-field__control:read-only{
  text-align: center;
  background: #fff;
}
::v-deep .van-cell__right-icon{
  margin-left: 0!important;
  background: transparent;
  transform: rotate(90deg);
}
</style>
